

/**
 *
 *  1. 暂时没有考虑 scale(1,1)  anchor(0.5,0.5) angle(0) 的影响.
 */

let SX;
let SY;

cc.Class({
    extends: cc.Component,

    properties: {

    },

    // LIFE-CYCLE CALLBACKS:

    onLoad () {

        let viewPort = cc.view._viewportRect;

        SX = viewPort.width / cc.winSize.width;
        SY = viewPort.height / cc.winSize.height;

        let sprite = this.node.getComponent(cc.Sprite);
        this.material = sprite.getMaterial(0);

        this.onUpdatePosition();

        this.time = 0;
    },

    onEnable(){
        cc.log('onEnable called!');
        this.node.on(cc.Node.EventType.POSITION_CHANGED,this.onUpdatePosition,this);
        this.node.on(cc.Node.EventType.SIZE_CHANGED,this.onUpdatePosition,this);
    },

    onDisable(){
        cc.log('onDisable called!');
        this.node.off(cc.Node.EventType.POSITION_CHANGED,this.onUpdatePosition,this);
        this.node.off(cc.Node.EventType.SIZE_CHANGED,this.onUpdatePosition,this);
    },

    onUpdatePosition(){

        if(!this.material){
            return;
        }

        cc.log(`onUpdatePosition called!`);
        let size = this.node.getContentSize();

        // u_left_bottom 需要转换到世界坐标系下
        let lb = cc.v2(this.node.x - size.width/2,this.node.y - size.height/2);
        let lbInWorld = this.node.parent.convertToWorldSpaceAR(lb);

        this.material.setProperty('u_left_bottom',{
            x:lbInWorld.x * SX,
            y:lbInWorld.y * SY
        });

        // TODO: 可以直接 通过 lbInWorld + size 去加速计算
        let rt = cc.v2(this.node.x + size.width/2,this.node.y + size.height/2);
        let rtInWorld = this.node.parent.convertToWorldSpaceAR(rt);

        this.material.setProperty('u_right_top',{
            x:rtInWorld.x * SX,
            y:rtInWorld.y * SY
        });
    },


    update (dt) {
        this.time += dt;
        if(this.material){
            this.material.setProperty('u_time',this.time);
        }
    },
});
